package com.linkwedo.saas.member;

import java.util.List;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.lang.RandomStringUtils;

import com.linkwedo.saas.datasource.ConnectionInfo;
import com.linkwedo.saas.datasource.ConnectionStrategy;
import com.linkwedo.saas.directory.JNDIService;
import com.linkwedo.saas.directory.LDAPService;
import com.linkwedo.saas.domain.member.RegisterCompanyVerify;
import com.linkwedo.saas.domain.member.User;

public class RegisterCompanyService {
	private User user;
	private RegisterCompanyDao registerCompanyDao;
	private BasicDataSource dynamicDataSource;

	public void registerCompany(User user) throws Exception {
		try {
			
			//创建数据库
			RegisterCompanyDao dao = getRegisterCompanyDao();
			ConnectionInfo connectionInfo = dao.saveCompany(user);
			
			//LDAP中注册员工及公司
			LDAPService.registerCompany(user, connectionInfo);
			
			//配置动态数据源中的连接信息
			ConnectionStrategy.reConfigDataSource(connectionInfo,
					dynamicDataSource);
			//绑定数据源至JNDI中
			JNDIService.bindDataSource(connectionInfo.getJndiURL(),
					dynamicDataSource);
		} catch (Exception e) {
			dynamicDataSource = null;
			throw e;
		}
	}

	public BasicDataSource getDynamicDataSource() {
		return dynamicDataSource;
	}

	public void setDynamicDataSource(BasicDataSource dynamicDataSource) {
		this.dynamicDataSource = dynamicDataSource;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public RegisterCompanyDao getRegisterCompanyDao() {
		return registerCompanyDao;
	}

	public void setRegisterCompanyDao(RegisterCompanyDao registerCompanyDao) {
		this.registerCompanyDao = registerCompanyDao;
	}

	/**
	 * 将注册公司的校验码存入数据库
	 * @param email
	 * @param company
	 * @return
	 * @throws Exception
	 */
	public String persistVerify(String email, String company) throws Exception {
		String verifyCode = RandomStringUtils.randomAlphanumeric(15);
		RegisterCompanyVerify verify = new RegisterCompanyVerify();
		verify.setEmail(email);
		verify.setCompany(company);
		verify.setVerifyCode(verifyCode);
		getRegisterCompanyDao().persistVerify(verify);
		return verifyCode;
	}

	/**
	 * 校验email和校验码是否存在
	 * @param email
	 * @param verifyCode
	 * @return
	 */
	public boolean verify(String email, String verifyCode) {
		RegisterCompanyVerify verify = new RegisterCompanyVerify();
		verify.setEmail(email);
		verify.setVerifyCode(verifyCode);
		List<RegisterCompanyVerify> result = getRegisterCompanyDao()
				.searchVerify(verify);
		return result.size() > 0 ? true : false;
	}

}
